#!/usr/bin/env python3

import copy as _copy

import tmm.web.lock.rwlock as _rwlock


class MessageBucket:
    """Bucket of messages."""

    def __init__(self, limit=None):
        """Initialize the object.

        :type limit: int | None
        :param limit: The size limit of the bucket (if no limit, use 'None').
        """

        self._data = []
        self._lock = _rwlock.ReadWriteLock()
        self._limit = limit

    def write_message(self, msg):
        """Write a message to the bucket.

        :type msg: bytes
        :param msg: The message.
        """

        #  Lock.
        self._lock.acquire_write()

        #  Free spaces to save the message.
        if self._limit is not None:
            while len(self._data) >= self._limit:
                self._data.pop(0)

        #  Write the message.
        self._data.append(msg)

        #  Unlock.
        self._lock.release()

    def read_messages(self, clear=True):
        """Read messages from the bucket.

        :type clear: bool
        :param clear: True if the messages should be removed after reading.
        :rtype: list[bytes]
        :return: The messages.
        """

        #  Lock.
        if clear:
            self._lock.acquire_write()
        else:
            self._lock.acquire_read()

        #  Read.
        result = _copy.copy(self._data)

        #  Clear.
        if clear:
            self._data.clear()

        #  Unlock.
        self._lock.release()

        return result
